<?php

namespace app\devices\controller;

use think\admin\Controller;
use think\admin\extend\CodeExtend;
use think\cache\driver\Redis;
use think\Db;
use think\DbManager;

/**
 * 柜点管理
 * Class Store
 * @package app\devices\controller
 */
class Store extends Controller
{
    /**
     * 绑定数据表
     * @var string
     */
    private $table = 'JcgStore';

    public $store_types = [1=>'超市', 2=>'车站', 3=>'加油站', 4=>'小区', 5=>'广场', 6=>'酒吧', 7=>'景区', 8=>'考场', 9=>'公园'];

    public $coo_types = [1=>'自营', 2=>'合作商', 3=>'销售柜子', 4=>'销售系统', 5=>'租赁'];

    public $arr_status = ['暂停营业','营业中'];

    /**
     * 柜点管理
     * @auth true
     * @menu true
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function index(){
        $map = [];

        $user = $this->app->session->get("user");
        $stores = [];
        if($user['id']!=10000){
            $authorize = str2arr($user['authorize'] ?? '');
            if(in_array(1, $authorize)){
                $stores = str2arr($user['stores'] ?? '');
                if($stores) {
                    $map[] = ['id', "in", $stores];
                }
            }

            if(in_array(3, $authorize)){
                $stores = $this->app->db->name("jcg_store")->where("sales_id", $user['id'])->column("id");
                $map[] = ['id', "in", $stores];
            }
        }
        $this->user_stores = $stores;
        $this->title = '柜点管理';
        $query = $this->_query($this->table);
        $query->like('name,address');
        $query->where($map)->order('id desc')->equal('status')->dateBetween('create_at')->page();
    }

    /**
     * 数据列表处理
     * @param array $data
     */
    protected function _page_filter(array &$data)
    {
        if($data){
            $store_ids = array_column($data, 'id');

            $yesterday = date("Y-m-d",strtotime("-1 day"));
            $wh = [
                ['store_id',"in",$store_ids],
                ['create_time',"between",[strtotime($yesterday), strtotime($yesterday.' 23:59:59')]],
                ['status','=',2]
            ];
            $times = $this->app->db->name("jcg_devices_order")->where($wh)->group("store_id")->column("count(id) as num,sum(reality_end_time-create_time) as last_time","store_id");
            foreach ($data as &$row){
                $time = $times[$row['id']]['last_time']??0;
                $num = $times[$row['id']]['num']??0;
                $row['order_times'] = ($num?round($time/$num/60/60,1):0)."小时";
            }
        }
    }

    /**
     * 添加柜点
     * @auth true
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function add()
    {
        $this->title = '添加柜点';
        $this->_form($this->table, 'form');
    }

    /**
     * 编辑柜点
     * @auth true
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function edit()
    {
        $this->title = '编辑柜点';
        $this->_form($this->table, 'form');
    }

    /**
     * 查看柜点
     * @auth true
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function see()
    {
        $this->title = '查看柜点';
        $this->_form($this->table, 'form');
    }

    /**
     * 设置分成比例
     * @auth true
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function share(){
        $this->title = '设置柜点分成比例';
        $this->_form($this->table, 'share');
    }

    /**
     * 数据表单处理
     * @param array $data
     */
    protected function _form_filter(array &$data)
    {
        if($this->app->request->isPost()){
            $user = $this->app->session->get("user");
            $data['s_id'] = $user['id'];

            if(isset($data['id'])){
                $redis = new Redis();
                $redis->delete("Store".$data['id']);
            }
        }else{
            $this->salesman = $this->app->db->name("system_user")->whereRaw("FIND_IN_SET('3', authorize)")->column("nickname",'id');
        }
    }

    /**
     * 表单结果处理
     * @param $result
     * @param $vo
     * @throws \think\db\exception\DbException
     */
    protected function _form_result($result, $vo)
    {
        if ($result && $this->request->isPost() && isset($vo['name']) && isset($vo['id'])) {
            $this->app->db->name("jcg_devices")->where("store_id", $vo['id'])->exp('device_name', "CONCAT('".$vo['name']." ',SUBSTRING_INDEX(device_name,' ',-1))")->update();
        }
    }

    /**
     * 修改柜点状态
     * @auth true
     * @throws \think\db\exception\DbException
     */
    public function state()
    {
        $this->_save($this->table, $this->_vali([
            'status.in:0,1'  => '状态值范围异常！',
            'status.require' => '状态值不能为空！',
        ]));
    }


    public function sss(){
        $user_ids = $this->app->db->name("jcg_devices_order")->where("status=1")->column("id, user_id, box_id");
        foreach ($user_ids as $row){
            dump($this->app->db->name("jcg_boxs")->where("id", $row['box_id'])->update(["user_id"=>$row['user_id'], 'box_status'=>2, 'is_lock'=>1]));
        }
    }

    /**
     * 删除柜点
     * @auth true
     * @throws \think\db\exception\DbException
     */
    public function remove()
    {
        $this->app->db->startTrans();
        $id = input("id",0);
        $id = $this->app->db->name("jcg_devices_order")->where(["store_id"=>$id, 'status'=>1, 'deleted'=>0])->value("id");
        if($id){
            $this->error("存在进行中的订单，不可删除柜点");
        }else{
            $this->_delete($this->table);
        }
    }

    /**
     * 删除结果处理
     * @param $result
     */
    protected function _remove_delete_result($result)
    {
        if ($result) {
            $id = input("id",0);
            try {
                $ids = $this->app->db->name("jcg_devices")->where(["store_id"=>$id])->column('id');
                if($ids) {
                    $this->app->db->name("jcg_devices")->where(["store_id"=>$id])->delete();
                    $this->app->db->name("jcg_device_fee")->where(["store_id"=>$id])->delete();
                    $this->app->db->name("jcg_boxs")->where("d_id", "in", $ids)->delete();
                }
                $this->app->db->commit();
            }catch (\Exception $e){
                $this->error("删除失败，请稍候再试！".$e->getMessage());
            }
        } else {
            $this->error("删除失败，请稍候再试！");
        }
    }
}